package NetStorage;

import java.io.*;
import java.net.Socket;
import java.util.Random;

/**
 * Created with IntelliJ IDEA.
 * User: Ratuil
 * Date: 19.03.13
 * Time: 12:23
 * To change this template use File | Settings | File Templates.
 */
public class NetStrorageClient {
    private static final int VALUE_LENGHT=10;
    private static final int KEY_RANGE=100;
    Random r;

    public static void main(String[] args) {
        new NetStrorageClient().run();
    }

    public void  run(){
        Socket socket=null;
        InputStream i=null;
        OutputStream o=null;
        ObjectOutputStream out=null;
        DataInputStream in=null;
        try{
            try{
                socket = new Socket("127.0.0.1", 6666);
                o = socket.getOutputStream();
                i = socket.getInputStream();
                out=new ObjectOutputStream(o);
                in=new DataInputStream(i);
                int itr=0;
                while(true){
                    Package pac=new Package();
                    r=new Random();
                    pac.com=r.nextInt(2);//0-get data,1-set data
                    //Package.Comm c = Package.Comm.values()[r.nextInt() % Package.Comm.values().length];
                    //pac.com=1;
                    pac.key=r.nextInt(KEY_RANGE);
                    pac.val=rndStr(VALUE_LENGHT);
                    out.writeObject(pac);
                    String s=in.readUTF();
                    itr++;
                    System.out.println(itr+". "+s);
                }
            }finally{
                o.close();
                i.close();
                socket.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String rndStr(int upToLen){
        Random r=new Random();
        int length=r.nextInt(upToLen);
        char[]arr=new char[length];
        for(int i=0;i<length;i++){
            int j=r.nextInt((int)'z');
            if(j<'a'){
                i--;
                continue;
            }
            arr[i]=(char)j;
        }
        return new String(arr);
    }
}
